﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace com.foxmail.wyyuan1991.Assignment.Solver.Dijstra
{
    /// <summary>
    /// PlanCourse 缓存从源节点到其它任一节点的最小权值路径＝》路径表
    /// </summary>
    public class PlanCourse
    {
        private Hashtable htPassedPath;
        private CostMatrix cm;
        #region ctor
        public PlanCourse(IList<INode> nodeList,CostMatrix c, string originID)
        {
            this.htPassedPath = new Hashtable();
            this.cm = c;

            INode originNode = null;

            #region 添加路径
            foreach (INode node in nodeList)
            {
                if (node.ID == originID)
                {
                    originNode = node;
                }
                else
                {
                    PassedPath pPath = new PassedPath(node.ID);
                    this.htPassedPath.Add(node.ID, pPath);
                }
            }

            if (originNode == null)
            {
                throw new Exception("The origin node is not exist !");
            }
            #endregion
            //初始化路径权重
            this.InitializeWeight(originNode);
        }

        private void InitializeWeight(INode originNode)
        {
            if ((originNode.ArcList == null) || (originNode.ArcList.Count == 0))
            {
                return;
            }
            //对初始节点的所有出边
            foreach (IArc edge in originNode.ArcList)
            {
                PassedPath pPath = this[edge.ENode.ID];
                if (pPath == null)
                {
                    continue;
                }
                
                if (cm[edge]< pPath.Weight)
                {
                    pPath.PassedIDList.Clear();
                    pPath.PassedArcList.Clear();
                    pPath.PassedIDList.Add(originNode);
                    pPath.PassedArcList.Add(edge);
                    pPath.Weight = cm[edge];
                }
            }
        }
        #endregion

        public PassedPath this[string nodeID]
        {
            get
            {
                return (PassedPath)this.htPassedPath[nodeID];
            }
        }
    }
}
